package com.enniswu.weitter.data.local;

import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Base64;

import com.enniswu.weitter.Application;

public class SPSupport {
    private static volatile SPSupport instance;
    private static final String KEY_SESSION = "sessionId";
    private static final String KEY_FIRST = "first";
    private static final String KEY_ID = "id";
    private static final String KEY_LANGUAGE = "language";
    private static final String KEY_THEME = "theme";

    private String sessionId;
    private int id;

    public static SPSupport getInstance() {
        if (instance == null) {
            synchronized (SPSupport.class) {
                if (instance == null) {
                    instance = new SPSupport();
                }
            }
        }
        return instance;
    }

    private SPSupport() {
        String temp = getSp().getString(KEY_SESSION, "");
        if (!TextUtils.isEmpty(temp)) {
            sessionId = new String(Base64.decode(temp, Base64.DEFAULT));
        }
        id = getSp().getInt(KEY_ID, 0);
    }

    private SharedPreferences getSp() {
        return PreferenceManager.getDefaultSharedPreferences(Application.getContext());
    }

    public void putFirst() {
        getSp().edit().putBoolean(KEY_FIRST, false).apply();
    }

    public boolean getFirst() {
        return getSp().getBoolean(KEY_FIRST, true);
    }

    public void putSessionId(@Nullable String sessionId) {
        if (sessionId == null)
            sessionId = "";
        this.sessionId = sessionId;
        sessionId = Base64.encodeToString(sessionId.getBytes(), Base64.DEFAULT);
        getSp().edit().putString(KEY_SESSION, sessionId).apply();
    }

    @Nullable
    public String getSessionId() {
        return sessionId;
    }

    public void putId(int id) {
        this.id = id;
        getSp().edit().putInt(KEY_ID, id).apply();
    }

    public int getId() {
        return id;
    }

    public void putLanguage(String language) {
        getSp().edit().putString(KEY_LANGUAGE, language).apply();
    }

    public String getLanguage() {
        return getSp().getString(KEY_LANGUAGE, "zh");
    }

    public void putTheme(String skinName) {
        getSp().edit().putString(KEY_THEME, skinName).apply();
    }

    public String getTheme() {
        return getSp().getString(KEY_THEME, "de");
    }
}
